<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Exception;

class SystemFileController extends BaseController
{
    /**
     * 系统文件
     */
    public function index(Request $request) {
        $param = $request->all();
        $fileObj = new \App\Services\FileManager('', $param);

        $datas = $fileObj->scanAllDir($param);
        $info_data = array_merge($datas['folder_infos'], $datas['file_infos']);

        $data = [
            'data' => $info_data,
            'path' => $param['path'] ?? '',
            'breadcrumbs' => $datas['breadcrumb'],
            'num_folders' => $datas['num_folders'],
            'num_files' => $datas['num_files'],
            'all_files_size' => $datas['all_files_size'],
            'partition_size' => $datas['partition_size'],
            'free_of_size' => $datas['free_of_size']
        ];

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
    }

    /**
     * 操作
     */
    public function handle(Request $request) {
        $param = $request->all();
        if (empty($param['action'])) {
            return api_response(self::STATUS_ERROR, '操作类型(action)不能为空', self::NOT_PARAM);
        }

        $fileObj = new \App\Services\FileManager('', $param);
        $action = $param['action'];
        if ($action == 'rename') {
            if (empty($param['from_name']) || empty($param['name'])) {
                return api_response(self::STATUS_ERROR, self::NOT_PARAM, '');
            }
            $result = $fileObj->rename($param);
            if (!$result) {
                return api_response(self::STATUS_ERROR, '失败', '');
            }
        } elseif ($action == 'delete') {
            if (empty($param['name'])) {
                return api_response(self::STATUS_ERROR, self::NOT_PARAM, '');
            }
            $result = $fileObj->delete($param);
        } elseif ($action == 'view') {
            if (empty($param['name'])) {
                return api_response(self::STATUS_ERROR, self::NOT_PARAM, '');
            }
            $result = $fileObj->viewer($param);
        }

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $result);
    }
}
